package com.mainbo.core.filter;

import com.mainbo.core.common.constant.Constants;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.shiro.service.UserAuthService;
import com.mainbo.modular.system.dao.PtRoleTypeMapper;
import com.mainbo.modular.system.dao.PtUserRoleMapper;
import com.mainbo.modular.system.model.PtAccount;
import com.mainbo.modular.system.model.PtRoleType;
import com.mainbo.modular.system.model.PtUserRole;
import com.mainbo.modular.system.service.IPtAccountService;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author moshang
 * @date 2020-03-15
 **/
public class  BackShiroCasUserFilter extends ShiroCasUserFilter {

    @Resource
    private IPtAccountService accountService;
    @Resource
    private PtRoleTypeMapper roleTypeMapper;

    @Override
    protected void localLogin(ServletRequest request, ServletResponse response) {
        Subject subject = getSubject(request, response);
        if (subject != null) {
            String uid = (String) subject.getPrincipal();
            setSession(uid, request);
            areadyLoin();
        }
    }

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        if (notAjaxRequest((HttpServletRequest) request)) {
            super.redirectToLogin(request, response);
        } else {
            try {
                response.setCharacterEncoding("UTF-8");
                response.getWriter()
                        .write("{\"statusCode\":\"301\", \"message\":\"\u767b\u5f55\u5931\u8d25\uff0c\u8bf7\u91cd\u8bd5\"}");
            } catch (IOException e1) {
                // do nothing
            }
        }
    }

    protected boolean notAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return requestedWith == null || !requestedWith.toLowerCase().contains("xmlhttprequest");
    }

    @Override
    protected void areadyLoin() {
        PtAccount acc = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        if (acc != null) {
            // 后序的登录信息补充
            MDC.put(Constants.MDC_CURRENT_USER_ID, acc.getId());
            MDC.put(Constants.MDC_CURRENT_USER_ACCOUNT, acc.getAccount());
            MDC.put(Constants.MDC_CURRENT_USER_NAME, acc.getUserInfo() != null ? acc.getUserInfo().getName() : "");
            PtUserRole userRole = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER_ROLE);
            if (userRole != null) {
                MDC.put(Constants.MDC_CURRENT_USER_ROLE, String.valueOf(userRole.getRoleId()));
            }
        }
    }

    protected void setSession(String userid, ServletRequest request) {
        HttpSession session = ((HttpServletRequest) request).getSession();
        if (userid != null && session.getAttribute(SessionKey.CURRENT_USER) == null) {
            PtAccount u = accountService.findAccountWithInfo(userid);
            session.setAttribute(SessionKey.CURRENT_USER, u);
            PtRoleType roleType= roleTypeMapper.selectById(u.getUserType());
            session.setAttribute(SessionKey.CURRENT_USER_ROLE, roleType);
        }
    }

}
